<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use Illuminate\Support\Facades\Cookie;

class AdminGetPower
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $cookie = $this->getCookie('login-cookie');
        if(!$cookie){
            return redirect()->action('IndexController@login')->withErrors(['已过期，请重新登陆！'])->withInput();
        }else{
            $this->setCookie('login-cookie',time(),7200);
        }
        $user = $request->session()->get('user');
        if(!empty($user)){
            if(!$user['name']){
                return redirect()->action('IndexController@login')->withErrors(['未获取到用户信息，请重新登陆！'])->withInput();
            }
            $users = User::where('name','=',$user['name'])->first();
            if(empty($users)){
                return redirect()->action('IndexController@login')->withErrors(['未获取到用户信息，请重新登陆！'])->withInput();
            }
            //更新缓存
            $request->session()->put('user',$users);
        }
        if(empty($user)){
            return redirect()->action('IndexController@login')->withErrors(['未获取到用户信息，请重新登陆！'])->withInput();
        }
        return $next($request);
    }
    public function setCookie($key,$value,$time){
        Cookie::queue($key, $value,$time);
        return;
    }
    // 获取cookie
    public function getCookie($key){
        return Cookie::get($key);
    }
}
